# coding=utf-8
from __future__ import print_function, absolute_import

from datetime import datetime, timedelta
from main_contracts import futures_contracts
import pandas as pd
from gm.api import *

# 可以直接提取数据，掘金终端需要打开，接口取数是通过网络请求的方式，效率一般，行情数据可通过subscribe订阅方式
# 设置token， 查看已有token ID,在用户-密钥管理里获取
set_token('0dc802db1a918f7c064237478e69b83a024028e7')


def set_specific_time(dt_obj, hour=0, minute=0, second=0):
    """
    修改datetime对象的时间部分
    参数:
        dt_obj (datetime): 原始datetime对象
        hour (int): 目标小时(0-23)
        minute (int): 目标分钟(0-59)
        second (int): 目标秒(0-59)
    返回:
        datetime: 新时间点的datetime对象
    """
    return dt_obj.replace(hour=hour, minute=minute, second=second)


def get_next_day(date_str):
    """
    计算给定日期的下一日
    参数:
        date_str (str): 格式为'YYYY-MM-DD'的日期字符串
    返回:
        str: 下一日的日期字符串，格式为'YYYY-MM-DD'
    """
    date_obj = datetime.strptime(date_str, '%Y-%m-%d')
    next_day = date_obj + timedelta(days=1)
    return next_day.strftime('%Y-%m-%d')


# 查询历史行情, 采用定点复权的方式， adjust指定前复权，adjust_end_time指定复权时间点
def get_daily_tick_history_by_symbol(symbol: str, spec_date: datetime):
    # print(symbol, spec_date)
    next_date = spec_date + timedelta(days=1)
    spec_date = set_specific_time(spec_date, 20, 0, 0)
    next_date = set_specific_time(next_date, 16, 0, 0)
    data = pd.DataFrame()
    try:
        data = history(symbol=symbol, frequency='tick', start_time=spec_date, end_time=next_date,
                       fields='symbol,open,high,low,price,cum_volume,cum_amount,cum_position,'
                              'trade_type,last_volume,last_amount,created_at,quotes',
                       adjust=ADJUST_NONE, adjust_end_time='2020-12-31', df=True)
    except Exception as e:
        print(e)

    # 完整格式化（含时区冒号分隔）
    if not data.empty:
        data['created_at'] = (
                data['created_at']
                .dt.strftime('%Y-%m-%d %H:%M:%S.%f%z')
                .str[:-2] + ':' + data['created_at'].dt.strftime('%z').str[-2:]
        )
        csv_filename = './' + spec_date.strftime('%Y-%m-%d') + '-' + symbol + '.csv'
        data.to_csv(csv_filename, index=False)
        # print(start_date)
        # print(next_date)
        # print(csv_filename)
        # print(data.size)
    else:
        print(f'{symbol}合约{spec_date}没有数据，为{data.size}')
    pass


def loop_date_in_range(symbol, start_date, end_date):
    """
    打印指定日期范围内的每一天
    参数:
        start_date (str): 开始日期，格式'YYYY-MM-DD'
        end_date (str): 结束日期，格式'YYYY-MM-DD'
    """

    current_date = start_date
    while current_date <= end_date:
        # print(current_date.strftime('%Y-%m-%d'))

        # next_date = get_next_day(current_date)
        get_daily_tick_history_by_symbol(symbol, current_date)
        current_date += timedelta(days=1)


def get_tick_history_main(start_date, end_date):
    start = datetime.strptime(start_date, '%Y-%m-%d')
    end = datetime.strptime(end_date, '%Y-%m-%d')

    # 测试交易所访问
    # print("CFFEX.IH 对应:", futures_contracts["CFFEX"]["IH"])
    # print("SHFE.CU 对应:", futures_contracts["SHFE"]["CU"])

    # get_daily_tick_history_by_symbol('CFFEX.TF', start)
    # get_daily_tick_history_by_symbol('SHFE.CU', start)
    # loop_date_in_range('GFEX.PS', start, end)
    # return

    # 遍历所有交易所
    for exchange, contracts in futures_contracts.items():
        # print(f"\n{exchange} 交易所合约:")
        for code, name in contracts.items():
            # print(f"{exchange}.{code}: {name}")
            symbol = f"{exchange}.{code}"
            # if exchange == 'CFFEX':
            # next_date = start_date + timedelta(days=1)
            # loop_date_in_range(symbol, next_date, end)
            # else:
            loop_date_in_range(symbol, start, end)
    pass


if __name__ == '__main__':
    get_tick_history_main('2025-07-08', '2025-07-15')
